#!/usr/bin/env zsh
# koushare ID recorder

source ./config.zsh

start_timestamp=$(date +%s)
LOGFILE="${LOG_DIR}koushare.${start_timestamp}.log"

LIVEINFO_JSON="${INFO_DIR}liveinfo."$id".$start_timestamp.json"
LIVEINFO_FIX_JSON="${INFO_DIR}liveinfo."$id".$start_timestamp.fix.json"
LIVEINFO_STRIP_JSON="${INFO_DIR}liveinfo."$id".$start_timestamp.fix.strip.json"

LIVEMETA_JSON="${INFO_DIR}livemeta."$id".$start_timestamp.json"
LIVEMETA_FIX_JSON="${INFO_DIR}livemeta."$id".$start_timestamp.fix.json"
LIVEMETA_STRIP_JSON="${INFO_DIR}livemeta."$id".$start_timestamp.fix.strip.json"

debug_mode=0
dryrun_mode=0
[[ -z $1 ]] && { exit 1; }
[[ ! -z $2 ]] && { debug_mode=1; }
if [[ ${2} = "D" ]]; then
	dryrun_mode=1
	echo "Dry Run"
fi

re='^[0-9]+$'
if ! [[ $1 =~ $re ]] ; then
	echo "Not a Number: $1" >&2
	exit 1
fi
echo "ID: $1 (PID: $$)"
id="$1"

header_content="Content-Type: application/json"
header_accept="Accept: application/json, text/plain, */*"
header_client="Client: front_web" # essential header
header_ua="User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
curl_method="POST"

id_data="{\"id\":\"$id\"}"
liveauthapi="https://core.api.koushare.com/live/v1/live/checkLiveAuth"

# query live info
liveinfo_json=$(curl -X $curl_method -H "$header_content" -H "$header_accept" -H "$header_client" -H "$header_ua" --data "$id_data" "$liveauthapi" 2>/dev/null)
# [[ $debug_mode -eq 1 ]] && { echo "LiveInfo json:\n$liveinfo_json"; }
# [[ $debug_mode -eq 1 ]] && { echo "$liveinfo_json" > "$id".$start_timestamp.test.liveinfo.json ; }
echo "$liveinfo_json" > "$LIVEINFO_JSON"

# get secret string
secret_string=$(echo $liveinfo_json | sed -e 's/\t/\\t/g' | jq -r .data.secret)
[[ -z $secret_string ]] && { echo "Secret Error!"; exit 1; }

getliveapi="https://core.api.koushare.com/live/v1/live/getLive?liveId=$1&secret=$secret_string"
livemeta_json=$(curl -H "$header_client" "$getliveapi" 2>/dev/null)
echo "$livemeta_json" > "$LIVEMETA_JSON"

# [[ $debug_mode -eq 1 ]] && { echo "LiveMeta json:\n$livemeta_json"; }

# cat metatest.json | sed -E -e ':a;N;$!ba;s|"brief.*status\":.,||g' | less
# cat myfile.json | tr -d '\n' | sed -E 's/"brief":"[^"]*",//g'
livemeta_json=$(echo $livemeta_json | tr -d '\n')
# [[ $debug_mode -eq 1 ]] && { echo "$livemeta_json" > "$id".$start_timestamp.test.livemeta.json ; }
# [[ $dryrun_mode -eq 1 ]] && { echo "Dry Run Ended."; exit 0; }

# the description part in livemeta json contains illegal html tags
python3 pagelivehandle.py "$LIVEMETA_JSON" "$LIVEMETA_FIX_JSON"

title_string=$(cat "$LIVEMETA_FIX_JSON" | sed -E -e 's|[\x00-\x1F]||g' | jq -r .data.title)
flvurl=$(cat "$LIVEMETA_FIX_JSON" | sed -E -e 's|[\x00-\x1F]||g' | jq -r .data.flvurl)
hlsurl=$(cat "$LIVEMETA_FIX_JSON" | sed -E -e 's|[\x00-\x1F]||g' | jq -r .data.hlsurl)

# check if already being recorded
# TODO: local lock file solution
result=$(sqlite3 "$DB_FILE" <<EOF
SELECT *
FROM recorded_list
WHERE room_id = $id AND status = 1
LIMIT 1;
EOF
)
if [[ -n "$result" ]]; then
    echo "Found record: $result. (Maybe $id is already being recorded?) Exit."
	exit 1
fi

# TODO: fallback handle
# archive
fastbackurl=$( )

# title_string
# https://stackoverflow.com/questions/9847288/is-it-possible-to-use-in-a-filename
title_string=$(echo "$title_string" | sed -E -e 's|/||g')
title_string=${title_string:0:$FILENAME_MAXCHARS}

echo "Title: $title_string\nHLS:$hlsurl"

# TODO: handle duplicated name properly
# timestamp=$(date +%s)
echo "$start_timestamp: recording [$id]; TN: ${title_string}" >> $LOGFILE
# TODO: use py module to extract the exact ext name

# insert into database
db_start_timestamp=$(date -d @$start_timestamp '+%Y-%m-%d %H:%M:%S')
# Insert a record
sqlite3 "$DB_FILE" <<EOF
INSERT INTO recorded_list (room_id, start, end, title, hostname, description, url, status)
VALUES ("$id", "$db_start_timestamp", NULL, "$title_string", 'N/A host', 'N/A description', "$hlsurl", 1);
EOF

# Retrieve the last inserted row's ID
# TODO: always return 0 but why? A: because every sqlite3 command makes a new connection to sqlite, but can't I preserve the connection in zsh?
# last_insert_id=$(sqlite3 "$DB_FILE" "SELECT last_insert_rowid();")
# echo "Last Inserted ID: $last_insert_id"

yt-dlp --quiet "$hlsurl" -o "${RECORD_DIR}[$id]${title_string}.${start_timestamp}.%(ext)s" # > "[${id}].${start_timestamp}.ytdlp.log" 2&1
rv=$?

db_end_timstamp=$(date '+%Y-%m-%d %H:%M:%S')
# Update the status of the record using the last_insert_id
# Can't use last_insert_id but dk why
result=$(sqlite3 "$DB_FILE" <<EOF
SELECT id
FROM recorded_list
WHERE room_id = $id AND status = 1
LIMIT 1;
EOF
)
if [[ -n "$result" ]]; then
    echo "Found record: $result"
	sqlite3 "$DB_FILE" <<EOF
UPDATE recorded_list
SET status = 0,
end = "$db_end_timstamp"
WHERE ROWID = $result;
EOF
else
    echo "No matching record found."
fi

echo "$(date +%s): [$id] DONE (retval=$rv); FN: [$id]${title_string}.$start_timestamp.%(ext)s" >> $LOGFILE
